package com.example.baidumap_a.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.example.baidumap_a.Activity.ChangePawActivity;
import com.example.baidumap_a.Activity.RechargeActivity;
import com.example.baidumap_a.entity.Ohuang;
import com.example.baidumap_a.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import com.example.baidumap_a.R;

public class MyFragment extends Fragment {
    private View view;
    private TextView textView_name, textView_balance;
    private Button btn_recharge, btn_password, btn_exit;
    private String name;
    private MyFgListener myFgListener;

    final OkHttpClient client = new OkHttpClient();
    private final static int  JSON_OK=0,JSON_NO=1;
    private User user;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        myFgListener = (MyFgListener) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_my, container, false);
        initView();
        return view;
    }

    private void initView() {
        textView_name = view.findViewById(R.id.text_username_myfg);
        textView_balance = view.findViewById(R.id.text_balance_myfg);
        btn_recharge = view.findViewById(R.id.btn_recharge_myfg);
        btn_password = view.findViewById(R.id.btn_password_myfg);
        btn_exit = view.findViewById(R.id.btn_exit_myfg);
        name = myFgListener.MyFgGetUsername();
        textView_name.setText("用户名："+name);
        btn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exitdialogshow();
            }
        });

        btn_recharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getContext(), RechargeActivity.class);
                intent.putExtra("username",name);
                startActivity(intent);
            }
        });

        btn_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getContext(), ChangePawActivity.class);
                intent.putExtra("username",name);
                startActivity(intent);
            }
        });
        if (name!=null)
        PostHttpRequest();//获取余额
    }

    private void exitdialogshow() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_exit, null);
        final Dialog dialog = new AlertDialog.Builder(getContext(), R.style.MyDialog).setView(view).create();

        Button quxiao = view.findViewById(R.id.dialog_btn_exit_no);
        Button queding = view.findViewById(R.id.dialog_btn_exit_ok);

        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    dialog.dismiss();
                    Ohuang.writefile(getContext(), "name.txt", "");
                    Ohuang.writefile(getContext(), "password.txt", "");
                    getActivity().finish();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog.show();
        //需要先显示再设置大小
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.7 * screenWidth);
        window.setAttributes(params);
    }


    private void PostHttpRequest() {
        RequestBody formBody = new FormBody.Builder()
                .add("username", name)
                .build();

        final Request request = new Request.Builder()
                .url("https://d30n971042.imdo.co/user/findUser")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                myHandler.sendEmptyMessage(JSON_NO);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String json = body.string();
                    Gson gson = new Gson();
                    Type type = new TypeToken<User>() {
                    }.getType();
                    user = gson.fromJson(json, type);
                    body.close();
                }

                myHandler.sendEmptyMessage(JSON_OK);
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case JSON_OK:
                    textView_balance.setText("余额：￥"+user.getMoney()+"元");
                    break;
                case JSON_NO:
                    Toast.makeText(getContext(),"网络错误",Toast.LENGTH_SHORT).show();
            }
        }

    };

    public interface MyFgListener {
        String MyFgGetUsername();
    }
}
